package com.tiger.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tiger.cache.RedisService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

import static java.util.concurrent.TimeUnit.SECONDS;

@Service
public class IpToAddress {
    @Value("${baidu.location}")
    String apiUrl;

    private final static String ipToAddressKey = "ipToAddress";

    private final RedisService redisService;


    public IpToAddress(RedisService redisService) {
        this.redisService = redisService;
    }

    public String convert(String ip, boolean isLock) {

        if(isLock) {
            ValueOperations<String, String> valueOps = redisService.template.opsForValue();

            String lockKey = "iptoa." + ip;
            boolean lock = Boolean.TRUE.equals(valueOps.setIfAbsent(lockKey, "1", 10, SECONDS));
            if(!lock) return null;
        }




        HashOperations<String, String, String> ops = redisService.template.opsForHash();
        String address = ops.get(ipToAddressKey, ip);


        if (address == null) {
            RestTemplate template = new RestTemplate();




            ResponseEntity<HashMap> response = template.getForEntity(String.format(apiUrl, ip), HashMap.class);

            int status = (int) response.getBody().get("status");

            if(status == 0) {
                HashMap<String, Object> content = (HashMap<String, Object>) response.getBody().get("content");
                HashMap<String, Object> address_detail = (HashMap<String, Object>) content.get("address_detail");

                address = (String) address_detail.get("city");

                ops.put(ipToAddressKey, ip, address);
            }



        }

        return address;
    }

    public String getAddress(String ip) {
        return convert(ip, false);
    }
}
